//
//  CGLView.m
//  tinygl
//
//  Created by baobaowang on 13-6-4.
//  Copyright (c) 2013年 jiajiawei. All rights reserved.
//

#import "CGLView.h"
#import "gl.h"

@implementation CGLView

- (id)initWithFrame:(CGRect)frame
{
    _glcontext = NULL;
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        char* bitmaps[0];
        bitmaps[0] = (char*)malloc(frame.size.width * frame.size.height * 16);
        _glcontext = ostgl_create_context(frame.size.width, frame.size.height, 16, (void**)bitmaps, 1);
        ostgl_make_current(_glcontext, 0);
    }
    return self;
}

- (void) setFrame:(CGRect)frame
{
    super.frame = frame;
    if ( _glcontext != NULL )
    {
        free(_glcontext->framebuffers[0]);
        
        char* bitmaps[0];
        bitmaps[0] = (char*)malloc(frame.size.width * frame.size.height * 16);
        _glcontext = ostgl_create_context(frame.size.width, frame.size.height, 16, (void**)bitmaps, 1);
        ostgl_make_current(_glcontext, 0);    }
}



- (void)drawRect:(CGRect)rect
{
    glEnable(GL_DEPTH_TEST);
    glClearColor(0.0f, 1.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    glViewport(0, 0, 320, 480);
    glFrustum(0, 320, 0, 480, 5, 10000);
    

    
    glBegin(GL_LINE_STRIP);
    glColor3f(1.0f, 0.0f, 0.0f);
    glVertex3f(0, 0, -6);
    glVertex3f(200, 200, -6);
    glEnd();
    
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

//    CGContextRef bitmapContext = CGBitmapContextCreate(_glcontext->framebuffers[0], _glcontext->xsize, _glcontext->ysize, 8, 32 * _glcontext->xsize, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
//    CGImageRef image = CGBitmapContextCreateImage(bitmapContext);
//    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, _glcontext->xsize, _glcontext->ysize), image);
//    CGColorSpaceRelease(colorSpace);
//    CGContextRelease(bitmapContext);
//    CGImageRelease(image);
    
    
    CGDataProviderRef provider = CGDataProviderCreateWithData( NULL, (char*)_glcontext->framebuffers[0], _glcontext->xsize * _glcontext->ysize * 2, NULL);
    CGImageRef   image = CGImageCreate(_glcontext->xsize, _glcontext->ysize, 5, 16, _glcontext->xsize*2,  colorSpace, kCGBitmapByteOrder16Little, provider, NULL, true, kCGRenderingIntentDefault);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, _glcontext->xsize, _glcontext->ysize), image);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(image);
}


@end
